package com.njlime.core.base.controller;

import com.alibaba.fastjson.JSONObject;
import com.njlime.core.exception.*;
import com.njlime.core.helper.PageBean;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.entities.User;
import com.njlime.sys.security.util.UserUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Controller基类
 * Created by Dean on 2017-7-18.
 */
@Controller
public class BaseController {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private HttpServletRequest request;

    /**
     * 获取当前登录用户
     * @return
     */
    public User getLoginUser(){
        User user = UserUtils.getUser();
        if(user == null){
            throw new SessionException("用户未登录，请重新登录");
        }
        return user;
    }

    /**
     * 获取当前用户的单位ID
     * @return
     */
    public Integer getLoginUserUnitId(){
        return getLoginUser().getUnit_id();
    }

    /**
     * 获取当前用户的单位
     * @return
     */
    public Unit getLoginUserUnit(){
        return getLoginUser().getUnit();
    }

    /**
     * 检查数据权限，所有单条数据操作必须调用
     * @param unit_id 检查的数据所属的ID
     * @param creator 检查的数据的创建者
     * @exception PermissionException 无权限时抛出该异常
     */
    public void checkDataPermission(Integer unit_id, Integer creator){
        boolean hasPermission = false;
        List<Unit> unitList = UserUtils.getUnitList();
        if(unitList == null || unitList.size() <= 0){
            if(getLoginUser().getId() == creator){
                hasPermission = true;
            }
        }else{
            for(Unit unit : unitList){
                if(unit_id.equals(unit.getId())){
                    hasPermission = true;
                    break;
                }
            }
        }
        if(!hasPermission){
            throw new PermissionException("没有操作权限！");
        }
    }

    /**
     * 返回列表
     *
     * @return
     */
    public String toJsonListData(PageBean pb) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resCode", ExceptionState.SUCCESS);
        JSONObject list = new JSONObject();
        list.put("totalCount", pb.getTotalCount());
        list.put("totalPage", pb.getTotalPage());
        list.put("pageSize", pb.getPageSize());
        if (pb.getMapList() != null) {
            list.put("pageCount", pb.getMapList().size());
        } else {
            list.put("pageCount", 0);
        }
        list.put("curPage", pb.getCurPage());
        list.put("list", pb.getMapList());
        if(pb.getMapList() == null){
            list.put("list", new ArrayList<Map<String,Object>>());
        }
        jsonObject.put("resultList", list);
        return JSON2String(jsonObject);
    }

    /**
     * 返回对象
     *
     * @param list
     * @return
     */
    public String toJsonListData(List<Map<String,Object>> list) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resCode", ExceptionState.SUCCESS);
        jsonObject.put("resultList", list);
        return JSON2String(jsonObject);
    }
    /**
     * 返回对象
     *
     * @param list
     * @return
     */
    public String toJsonListData(Object list) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resCode", ExceptionState.SUCCESS);
        jsonObject.put("resultList", list);
        return JSON2String(jsonObject);
    }
    /**
     * 返回成功
     *
     * @return
     */
    public String toJsonSuccessData() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resCode", ExceptionState.SUCCESS);
        return JSON2String(jsonObject);
    }

    /**
     * 返回成功
     *
     * @param object 需要返回的数据
     * @return
     */
    public String toJsonSuccessData(Object object) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resCode", ExceptionState.SUCCESS);
        if(object!=null) {
            jsonObject.put("resultList", object);
        }else{
            jsonObject.put("resultList", new Object());
        }
        return JSON2String(jsonObject);
    }

    /**
     * 返回失败结果，并带上message及结果
     *
     * @param errorCode
     * @param errorMessage
     * @param resultObj
     * @return
     */
    public String toJsonErrorData(Integer errorCode, String errorMessage, Object resultObj) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resCode", errorCode);
        jsonObject.put("resultList", resultObj);
        jsonObject.put("message", errorMessage);
        return JSON2String(jsonObject);
    }

    /**
     * 返回失败结果
     *
     * @param errorCode    错误码
     * @param errorMessage 错误信息
     * @return
     */
    public String toJsonErrorData(Integer errorCode, String errorMessage) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resCode", errorCode);
        jsonObject.put("message", errorMessage);
        return JSON2String(jsonObject);
    }

    /**
     * 返回失败结果(默认错误)
     *
     * @param errorCode    错误码
     * @return
     */
    public String toJsonErrorData(Integer errorCode) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("resCode", errorCode);
        jsonObject.put("message", ExceptionState.getExceptionMsg(errorCode));
        return JSON2String(jsonObject);
    }

    /**
     * 返回json字符串
     * @param jsonObject json对象
     * @return json字符串
     */
    private String JSON2String(JSONObject jsonObject){
        jsonObject.put("permission", request.getAttribute("permission"));
        return jsonObject.toJSONString();
    }


}
